package com.qy139.auth.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qy139.auth.mapper.TabUserMapper;
import com.qy139.auth.mapper.UserLeaveMapper;
import com.qy139.auth.service.ITabUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qy139.entity.TabUser;
import com.qy139.entity.UserLeave;
import com.qy139.util.Result;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuhaochen
 * @since 2021-12-01
 */
@Service
public class TabUserServiceImpl extends ServiceImpl<TabUserMapper, TabUser> implements ITabUserService {
    @Resource
    private TabUserMapper userMapper;
    @Resource
    private UserLeaveMapper userLeaveMapper;

    @Override
    public List<String> findRolesById(Integer id) {
        return userMapper.findRolesById(id);
    }

    @Override
    public IPage<TabUser> selectAllUser(Page<TabUser> page, String name) {
        return userMapper.selectAllUser(page,name);
    }

    @Override
    public Result addUser(TabUser tabUser) {
        System.out.println("用户的名字是:"+tabUser.getName()+"密码是"+tabUser.getPwd());
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(tabUser.getPwd());
        tabUser.setPwd(password);
        return new Result(userMapper.insert(tabUser));
    }

    @Override
    public Result updUser(TabUser tabUser) {
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(tabUser.getPwd());
        tabUser.setPwd(password);
        return new Result(userMapper.updateById(tabUser));
    }

    @Transactional
    @Override
    public Result deleteUser(TabUser tabUser) {
        Integer id = tabUser.getId();
        Integer operatorId = tabUser.getOperatorId();
        Date date = userMapper.getHireDate(id);
        userMapper.deleteById(id);
        UserLeave ul = new UserLeave();
        ul.setUserId(id);
        ul.setOperatorId(operatorId);
        ul.setHiredate(date);
        ul.setFiredate(new Date());
        userLeaveMapper.insert(ul);
        return new Result(200,"success");
    }
}
